package com.example.springboot_jdk8.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.springboot_jdk8.config.CacheCurConfig;
import com.example.springboot_jdk8.config.MdmConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cl0403
 */
@Slf4j
public class MdmUtil {

    private static MD5 md5 = null;

    static {
        md5 = MD5.create();
    }

    public static String buildReqDataJson(HashMap<String, Object> requestParam){
        HashMap<String, Object> map = new HashMap<>();
        map.put("dataJson", requestParam);
        return JSONUtil.toJsonStr(map);
    }

    /**
     * 构建请求的base64 data数据
     * @param jsonBody
     * @return
     */
    public static String buildReqData(String jsonBody){
        MdmConfig config = CacheCurConfig.getConfig();
        Map<String, String> header = new HashMap<>();
        String sign = md5Hex(config.getAppId(), jsonBody, config.getAppKey());
        header.put("appid", config.getAppId());
        header.put("sign", sign);
        Map<String, Object> message = new HashMap<>();
        message.put("header", header);
        message.put("body", jsonBody);//body为json字符串
        return new String(Base64.getEncoder().encode((JSONUtil.toJsonStr(message)).getBytes()));
    }

    /**
     * 账号+body(json字符串)+密码  md5hex加密后转英文大写生成信签sign
     * @param appId
     * @param body
     * @param appKey
     * @return
     */
    public static String md5Hex(String appId,String body,String appKey){
        return md5.digestHex(appId + body + appKey).toUpperCase();
    }



    public static JSONObject request(String data,String url){
        HttpResponse response = HttpUtil.createPost(url)
                .timeout(10 * 1000)
                .form("data",data)
                .execute();
        validateResp(response);
        return JSONUtil.parseObj(response.body()).getJSONObject("body");
    }


    static void validateResp(HttpResponse response) {
        log.info("==== 验证响应: {} ====", response.toString());
        JSONObject jsonObject = JSONUtil.parseObj(response.body());
        JSONObject header = jsonObject.getJSONObject("header");
        Integer errCode = header.getInt("code");
    }



    /*
     * 循环出部门全路径,以及level
     * @param subCompany 公司
     * @param departments 所属公司下的全部组织
     * */
    public static void loopDeptPathAndLevel(List<JSONObject> departments) {
        //如果是全量拉取,可在内存中组装路径
        //增量无法返回所有组织,只能用数据库中的数据二次组装
        if (!CacheCurConfig.getConfig().getIsFullPull()) {
            return;
        }
        for (JSONObject department : departments) {
            int level = 1;
            //组织中文名路径
            StringBuilder namePath = new StringBuilder();
            //组织唯一标识路径
            StringBuilder uniquePath = new StringBuilder();
            namePath.append("/").append(department.getStr("orgName"));
            uniquePath.append("/").append(department.getStr("orgUniCode"));
            String parentId = department.getStr("orgParentCode");
            while (!StrUtil.isEmpty(parentId)) {
                String pid = parentId;
                JSONObject parent = departments.stream().filter(p -> p.getStr("orgUniCode").equals(pid)).findFirst().orElse(null);
                if (parent == null) {
                    break;
                }
                namePath.insert(0, "/" + parent.getStr("orgName"));
                uniquePath.insert(0, "/" + parent.getStr("orgUniCode"));
                parentId = parent.getStr("orgParentCode");
                level++;
            }
            department.set("level",level);
            department.set("appOrgNamePath", namePath.toString());
            department.set("appOrgUniquePath", uniquePath.toString());
            level = 1;
        }
    }
}

